package dk.viauc.friendlocator;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class NameActivity extends Activity {
	private Button set;
	private EditText nameField;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_name);
		final Intent mainActivity = new Intent(this, MainActivity.class);

		set = (Button) findViewById(R.id.button1);
		nameField = (EditText) findViewById(R.id.editText1);
		try {
			FileInputStream fis = openFileInput("name.txt");
			InputStreamReader inputStreamReader = new InputStreamReader(fis);
		    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			Globals.NAME=bufferedReader.readLine();
		} catch (Throwable e) {
			Toast.makeText(this.getBaseContext(),"problem reading name "+ e.toString(), 
	                Toast.LENGTH_SHORT).show();
		}
		if (Globals.NAME == null || Globals.NAME == "") {

			nameField.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start,
						int before, int count) {

					if (nameField.getText().toString().length() < 3)
						set.setOnClickListener(null);
					else {
						set.setOnClickListener(new View.OnClickListener() {

							@Override
							public void onClick(View v) {
								try {
									FileOutputStream fos = openFileOutput(
											"name.txt", Context.MODE_PRIVATE);
									fos.write(nameField.getText().toString()
											.getBytes());
									fos.close();
								} catch (Throwable e) {
								}
								Globals.NAME = nameField.getText().toString();
								startActivity(mainActivity);
								finish();
							}
						});
					}
				}

				@Override
				public void beforeTextChanged(CharSequence s, int start,
						int count, int after) {
				}

				@Override
				public void afterTextChanged(Editable s) {
				}
			});

		} else {
			startActivity(mainActivity);
			finish();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
